const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const scoreElement = document.getElementById('score');
const nextPieceCanvas = document.getElementById('nextPieceCanvas');
const nextPieceCtx = nextPieceCanvas.getContext('2d');

canvas.width = 300;
canvas.height = 600;
nextPieceCanvas.width = 120;
nextPieceCanvas.height = 120;

const BOARD_WIDTH = 10;
const BOARD_HEIGHT = 20;
let board = Array(BOARD_HEIGHT).fill().map(() => Array(BOARD_WIDTH).fill(0));

const SHAPES = [
    [[1, 1, 1, 1]],
    [[1, 1], [1, 1]],
    [[1, 1, 1], [0, 1, 0]],
    [[1, 1, 1], [1, 0, 0]],
    [[1, 1, 1], [0, 0, 1]],
    [[1, 1, 0], [0, 1, 1]],
    [[0, 1, 1], [1, 1, 0]]
];

const COLORS = [
    '#FF0000', '#00FF00', '#0000FF',
    '#FFFF00', '#FF00FF', '#00FFFF', '#FFA500'
];

let currentPiece = null;
let currentPosition = { x: 0, y: 0 };
let nextPiece = null;
let score = 0;

function createNewPiece() {
    if (!nextPiece) {
    const randomIndex = Math.floor(Math.random() * SHAPES.length);
    currentPiece = {
        shape: SHAPES[randomIndex],
        color: COLORS[randomIndex]
    };
        const nextIndex = Math.floor(Math.random() * SHAPES.length);
        nextPiece = {
            shape: SHAPES[nextIndex],
            color: COLORS[nextIndex]
        };
    } else {
        currentPiece = nextPiece;
        const nextIndex = Math.floor(Math.random() * SHAPES.length);
        nextPiece = {
            shape: SHAPES[nextIndex],
            color: COLORS[nextIndex]
        };
    }
    currentPosition.x = Math.floor(BOARD_WIDTH / 2) - 
                       Math.floor(currentPiece.shape[0].length / 2);
    currentPosition.y = 0;
    drawNextPiece();
}

function checkCollision(offsetX, offsetY) {
    for (let y = 0; y < currentPiece.shape.length; y++) {
        for (let x = 0; x < currentPiece.shape[y].length; x++) {
            if (currentPiece.shape[y][x]) {
                const newX = currentPosition.x + x + offsetX;
                const newY = currentPosition.y + y + offsetY;
                if (newX < 0 || newX >= BOARD_WIDTH ||
                    newY >= BOARD_HEIGHT ||
                    board[newY] && board[newY][newX]) {
                    return true;
                }
            }
        }
    }
    return false;
}

function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    for (let y = 0; y < BOARD_HEIGHT; y++) {
        for (let x = 0; x < BOARD_WIDTH; x++) {
            if (board[y][x]) {
                ctx.fillStyle = board[y][x];
                ctx.fillRect(x * 30, y * 30, 29, 29);
            }
        }
    }

    if (currentPiece) {
        ctx.fillStyle = currentPiece.color;
        for (let y = 0; y < currentPiece.shape.length; y++) {
            for (let x = 0; x < currentPiece.shape[y].length; x++) {
                if (currentPiece.shape[y][x]) {
                    ctx.fillRect(
                        (currentPosition.x + x) * 30,
                        (currentPosition.y + y) * 30,
                        29, 29
            );
                }
            }
        }
    }
}

function drawNextPiece() {
    nextPieceCtx.clearRect(0, 0, nextPieceCanvas.width, nextPieceCanvas.height);
    if (!nextPiece) return;

    const cols = nextPiece.shape[0].length;
    const rows = nextPiece.shape.length;
    const startX = (nextPieceCanvas.width - cols * 30) / 2;
    const startY = (nextPieceCanvas.height - rows * 30) / 2;

    nextPieceCtx.fillStyle = nextPiece.color;
    for (let y = 0; y < rows; y++) {
        for (let x = 0; x < cols; x++) {
            if (nextPiece.shape[y][x]) {
                nextPieceCtx.fillRect(
                    startX + x * 30,
                    startY + y * 30,
                    29, 29
                );
            }
        }
    }
}

function mergePiece() {
    for (let y = 0; y < currentPiece.shape.length; y++) {
        for (let x = 0; x < currentPiece.shape[y].length; x++) {
            if (currentPiece.shape[y][x]) {
                board[currentPosition.y + y][currentPosition.x + x] = 
                    currentPiece.color;
            }
        }
    }
}

function checkLines() {
    let linesCleared = 0;
    for (let y = BOARD_HEIGHT - 1; y >= 0; y--) {
        if (board[y].every(cell => cell !== 0)) {
            board.splice(y, 1);
            board.unshift(Array(BOARD_WIDTH).fill(0));
            linesCleared++;
            y++;
            }
    }
    if (linesCleared > 0) {
        score += linesCleared * 100;
        scoreElement.textContent = score;
    }
}

function gameLoop() {
    if (!checkCollision(0, 1)) {
        currentPosition.y++;
    } else {
        mergePiece();
        checkLines();
        createNewPiece();
        if (checkCollision(0, 0)) {
            alert('游戏结束！得分: ' + score);
            board = Array(BOARD_HEIGHT).fill().map(() => 
                Array(BOARD_WIDTH).fill(0));
            score = 0;
            scoreElement.textContent = score;
        }
    }
    draw();
}

document.addEventListener('keydown', (e) => {
    switch(e.key) {
        case 'ArrowLeft':
            if (!checkCollision(-1, 0)) {
                currentPosition.x--;
                draw();
            }
            break;
        case 'ArrowRight':
            if (!checkCollision(1, 0)) {
                currentPosition.x++;
                draw();
            }
            break;
        case 'ArrowUp':
            const rotated = currentPiece.shape[0].map((_, i) =>
                currentPiece.shape.map(row => row[i]).reverse()
            );
            const originalShape = currentPiece.shape;
            currentPiece.shape = rotated;
            if (checkCollision(0, 0)) {
                currentPiece.shape = originalShape;
            } else {
                draw();
            }
            break;
        case 'ArrowDown':
            if (!checkCollision(0, 1)) {
                currentPosition.y++;
                draw();
            }
            break;
    }
});

createNewPiece();
draw();
const gameInterval = setInterval(gameLoop, 1000);

canvas.addEventListener('click', () => {
    if (confirm('重新开始游戏？')) {
        board = Array(BOARD_HEIGHT).fill().map(() => 
            Array(BOARD_WIDTH).fill(0));
        score = 0;
        scoreElement.textContent = score;
        currentPiece = null;
        nextPiece = null;
        createNewPiece();
        draw();
    }
});